package com.zis.wechat.api.web;

import com.alibaba.fastjson.JSON;
import com.zis.common.AuctProperties;
import com.zis.utils.StringUtils;
import com.zis.wechat.api.config.WechatPage;
import com.zis.wechat.api.config.WxConstant;
import com.zis.wechat.api.inter.IWechatUserInter;
import com.zis.wechat.model.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by wangshen 2018/1/2
 */
@Controller
@RequestMapping("/api/wechat/oauth")
public class OAuthController {

    private static final Logger logger = LoggerFactory.getLogger(OAuthController.class);

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    @Qualifier("auctProperties")
    private AuctProperties auctProperties;

    @Autowired
    private IWechatUserInter wechatUserInter;

    private static String httpURL = "";//默认跳转到404

    private String template = "wechat";//模版名称

    /**
     * 微信页面转发控制器
     * @param accountId
     * @param code 用户授权code
     * @param state 页面标识
     * @return
     */
    @RequestMapping(value = "/{accountId}/page", method = RequestMethod.GET)
    public String pageController(@PathVariable("accountId") String accountId, @RequestParam("code") String code, @RequestParam("state") String state){
        httpURL = auctProperties.getHost() + "404.html";
        if(accountId==null || accountId.equals("")){
            return "redirect:"+httpURL;
        }
        Account account = (Account) redisTemplate.opsForHash().get(WxConstant.WECHAT_ACCOUNT_KEY, accountId);
        //判断请求是否携带appid，并且验证携带的appid是否为系统注册的公众号
        if(!StringUtils.validityStr(new String[] { state, code }) || account == null){
            return "redirect:"+httpURL;
        }
        String token = wechatUserInter.oauthUser(code, accountId);
        if(token.equals("")){
            return "redirect:"+httpURL;
        }
        httpURL = auctProperties.getHost() +"#"+ WechatPage.PAGE_URL.get(state);
        httpURL += "?token="+token;
        //token是与后台交互的用户标示
        return "redirect:"+httpURL;
    }
}
